package com.wy.panda.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.cache.CacheProperties.Redis;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * 缓存配置
 * @author wangyuan
 * @since 2021年1月18日 下午11:59:48
 */
@Configuration
@EnableCaching(mode = AdviceMode.PROXY) //ASPECTJ时，类内部调用也可以走缓存
public class CacheConfig extends CachingConfigurerSupport {
    
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeKeysWith(SerializationPair.fromSerializer(RedisSerializer.string()));
        config = config.serializeValuesWith(SerializationPair.fromSerializer(RedisSerializer.json()));
        
        Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.computePrefixWith(new CacheKeyPrefix() {
                
                @Override
                public String compute(String cacheName) {
                    return redisProperties.getKeyPrefix() + cacheName + ":";
                }
            });
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        
        return config;
    }
}
